package com.ds.infra.rpc.autoconfigure;

import com.ds.infra.rpc.core.serializer.JacksonSerializer;
import com.ds.infra.rpc.core.serializer.Serializer;
import com.ds.infra.rpc.properties.RpcConsumerProperties;
import com.ds.infra.rpc.properties.RpcProperties;
import com.ds.infra.rpc.properties.RpcProviderProperties;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 作用：RPC自动配置主类
 *
 * @author WeiShaoying
 */
@Configuration
@EnableConfigurationProperties({RpcProperties.class/*, RpcProviderProperties.class, RpcConsumerProperties.class*/})
// @ConditionalOnProperty(prefix = "rpc", name = "role")
@ConditionalOnExpression(
        "!T(org.springframework.util.StringUtils).isEmpty('${rpc.role:}') " +
                "&& ('${rpc.role}'.equals('provider') || '${rpc.role}'.equals('consumer'))"
)
@Slf4j
public class RpcAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public ObjectMapper rpcObjectMapper() {
        log.info("====RpcAutoConfiguration Create ObjectMapper");
        return new ObjectMapper()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) // 忽略未知字段
                .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
                .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
                .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                ;
    }

    @Bean
    @ConditionalOnMissingBean
    public Serializer serializer() {
        log.info("====RpcAutoConfiguration Create JacksonSerializer");
        return new JacksonSerializer();
    }

    // public Serializer serializer(RpcProperties properties) {
    //     Serializer serializer = switch (properties.getSerializer()) {
    //         case JACKSON -> new JacksonSerializer();
    //         // 其他序列化实现...
    //         default -> throw new IllegalArgumentException("Unsupported serializer");
    //     };
    //     SerializerFactory.init(serializer); // 关键初始化！
    //     return serializer;
    // }
}
